/*
 *  Copyright (c) 2011 Lukáš Karas <lukas.karas@centrum.cz>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License version 2 as
 *  published by the Free Software Foundation;
 *
 *  Software distributed under the License is distributed on an "AS IS"
 *  basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
 *
 *  See the GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

package cz.karry.jtw;

/**
 *
 * @author karry
 */
public abstract class AbstractPoolingThread implements Runnable {

  protected final Object lock = new Object();
  protected long poolTime;
  protected boolean running = false;
  protected String name = "poolThread";

  public AbstractPoolingThread() {
  }

  public boolean start(long poolTime) {
    synchronized (lock) {
      if (running)
        return false;
      this.poolTime = poolTime;
      running = true;
      (new Thread(this, name)).start();
      return true;
    }
  }

  public boolean stop() {
    synchronized (lock) {
      if (!running)
        return false;
      running = false;
      lock.notifyAll();
      return true;
    }
  }

  @Override
  public void run() {
    synchronized (lock) {
      while (running) {
        doJob();
        long start = System.currentTimeMillis();
        while (running && System.currentTimeMillis() - start < poolTime) {
          try {
            lock.wait(poolTime - (System.currentTimeMillis() - start));
          } catch (InterruptedException ex) {
            // ignore this exception
          }
        }
      }
    }
  }

  abstract void doJob();
}
